import poplib
import random
import traceback
from selenium import webdriver
import time
import pymongo
from selenium.common.exceptions import NoSuchElementException, WebDriverException
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.proxy import Proxy, ProxyType
import redis
import requests


def reg_confirm3(username, password):
    proxys = conn.smembers('un_proxy')
    proxy = random.choice([i.decode() for i in proxys if i and b'@' not in i])
    myProxy = proxy.strip("http://")
    print(myProxy)
    proxy = Proxy({
        'proxyType': ProxyType.MANUAL,
        'httpProxy': myProxy,
        'ftpProxy': myProxy,
        'sslProxy': myProxy,
        'noProxy': ''  # set this value as desired
    })
    options = Options()
    options.headless = True
    try:
        driver = webdriver.Firefox(options=options, proxy=proxy)
        driver.get("https://mail.163.com/?msg=authfail#return")
        time.sleep(1)

        driver.switch_to.frame(2)
        name = driver.find_element_by_xpath('//input[@name="email"]')
        name.clear()
        pw = driver.find_element_by_xpath('//input[@name="password"]')
        pw.clear()
        btn = driver.find_element_by_xpath('//*[@id="dologin"]')
        name.send_keys(username)
        pw.send_keys(password)
        btn.click()
    except Exception as e:
        driver.quit()
        raise e
    # driver.switch_to_default_content()

    time.sleep(2)
    # driver.save_screenshot('tmp1.png')
    # driver.switch_to_frame(2)
    try:
        btn2 = driver.find_element_by_xpath("//*[contains(text(), '继续登录')]")
        btn2.click()
        time.sleep(2)
        driver.switch_to_default_content()
    except WebDriverException:
        driver.switch_to_default_content()
        pass
        traceback.print_exc()
    except NoSuchElementException:
        # driver.close()
        driver.quit()
        return {'code': 6}

    #
    try:
        mail = driver.find_elements_by_xpath("//*[contains(text(), '收件箱')]")
        if not mail:
            return None

        driver.get('https://login.189.cn/web/login')
        time.sleep(1)
        wangyi = driver.find_element_by_xpath('//*[@id="wyloginbtn"]')
        wangyi.click()
        handles = driver.window_handles
        #
        driver.switch_to.window(handles[1])
        time.sleep(1)
        login_btn = driver.find_element_by_xpath('//*[@id="dologin"]')
        login_btn.click()
        time.sleep(1)
        #
        driver.switch_to.window(handles[0])

        cookies = ";".join("{name}={value}".format(**i) for i in driver.get_cookies())
        print(cookies)
        return cookies
    finally:
        driver.quit()

if __name__ == '__main__':
    conn = redis.Redis(db=0)
    client = pymongo.mongo_client.MongoClient('mongodb://cs_user:cmcc5188@localhost:12018/cs_recharge')
    db = client.cs_recharge
    coll = db.cmcc_username

    #
    while True:
        objs = coll.find({"cookies": {"$eq": None}, "is_reg": {"$ne": '5'}}).limit(5)
        for obj in objs:
            print(obj)
            if "163.com" not in obj['username']:
                continue
            try:
                cookies = reg_confirm3(obj['username'], obj['emailpasswd'])
                if cookies:
                    coll.update_one(obj, {"$set": {"cookies": cookies}})
                    conn.rpush("ctcc_user", obj['username'])
            except Exception:
                traceback.print_exc()

        print("休息一下")
        time.sleep(1)
